<template>
  <el-upload
    :style="{ width: boxWidth }"
    :action="action"
    name="content"
    :data="{ fileName: '' }"
    :headers="headers"
    :multiple="multiple"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :on-error="handleError"
    :on-remove="handleRemove"
    :limit="limit"
    v-bind="$attrs"
    v-on="$listeners"
  >
    <div style="text-align: left">
      <el-button style="float: left"
        ><i class="el-icon-plus"></i> 点击上传</el-button
      >
      <div slot="tip" class="explain-txt2 tip">{{ showTip }}</div>
    </div>
  </el-upload>
</template>

<script>
import { getFileByFileId } from '@/api/file-controller';

function noop() {}

import { basePath, filePathPrefix } from '@/utils/request';
import { getToken } from '@/utils/auth';

export default {
  name: 'DocumentUpload',
  props: {
    fileId: {
      type: String,
      default: '',
    },
    value: {
      type: String,
      default: '',
    },
    boxWidth: {
      type: String,
      default: '100%',
    },
    action: {
      type: String,
      default: basePath + '/pub/file',
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    tips: {
      type: String,
      default: '',
    },
    sizeLimit: {
      type: Number,
      default: 5000,
    },
    limit: {
      type: Number,
    },
    uploadSuccess: {
      type: Function,
      default: noop,
    },
  },
  data() {
    return {
      fileList: [],
      elList: [],
      fileIdValue: '',
    };
  },
  created() {},
  mounted() {
    this.getFile();
  },
  computed: {
    showTip() {
      return this.tips
        ? this.tips
        : '支持pdf格式，5M以内，' +
            (this.multiple ? '支持上传多个' : '单一文件');
    },
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
  },
  watch: {
    value(to, from) {
      if (to && to !== this.fileIdValue) {
        this.getFile();
      }
    },
  },
  methods: {
    getFile() {
      if (!this.value) return;
      let tmp = this.value.split(',');
      this.fileList = [];
      tmp.forEach((item, i) => {
        getFileByFileId(item).then((res) => {
          this.$set(this.fileList, i, {
            name: res.data.fileName,
            url: filePathPrefix + res.data.fileUrl,
            fileId: res.data.fileId,
          });
        });
      });
    },

    beforeUpload(file) {
      if (this.sizeLimit > 0 && file.size > this.sizeLimit * 1024) {
        this.$message.error('文件大小超出限制！');
        return false;
      }
      this.$message.info('文件正在上传，请勿离开或刷新此页面');
    },
    handleSuccess(res, file, fileList) {
      if (!!res.code) {
        this.handleError(res);
      } else {
        this.fileList = fileList;
        if (this.multiple) {
          let temp = [];
          this.fileList.forEach((item) => {
            if (!item.hasOwnProperty('fileId')) {
              item.fileId = item.response.data.fileId;
              item.url = filePathPrefix + item.response.data.fileUrl;
            }
            temp.push(item.fileId);
          });
          this.fileIdValue = temp.join(',');
        } else {
          this.fileList = [file];
          this.fileIdValue = res.data.fileId;
        }
        this.$message.closeAll();
        this.$message.success('文件上传成功');
        this.$emit('input', this.fileIdValue);
        this.$emit('change', this.fileIdValue);
        this.uploadSuccess(fileList);
      }
    },
    handleError(err, file, fileList) {
      this.$message.closeAll();
      this.$message.error('文件上传失败，请重试');
      this.$emit('upload-error', err);
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      let temp = [];
      this.fileList.forEach((item) => {
        temp.push(item.fileId);
      });
      this.fileIdValue = temp.join(',');
      this.$emit('input', this.fileIdValue);
      this.$emit('change', this.fileIdValue);
    },
  },
};
</script>

<style scoped lang="scss">
.tip {
  margin-left: 10px;
  float: left;
}
</style>
